<template>
    <div>
        <el-dialog :title="props.isAdd ? '添加商品' : '编辑商品'" center v-model="props.isShow" :before-close="beforeClose">
            <el-form :model="goodsForm" :rules="rules" ref="goodsRef">
                <el-form-item label="一级分类" :label-width="formLabelWidth" prop="first_cateid">
                    <el-select placeholder="请选择" v-model="goodsForm.first_cateid" @change="changeCate(false)">
                        <el-option v-for="item in store.getters['cate/getCate']" :key="item.id" :label="item.catename"
                            :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="二级分类" :label-width="formLabelWidth" prop="second_cateid">
                    <el-select v-model="goodsForm.second_cateid" placeholder="请选择">
                        <el-option v-for="item in cateArr.data" :key="item.id" :label="item.catename" :value="item.id" />
                    </el-select>
                </el-form-item>

                <el-form-item label="商品名称" :label-width="formLabelWidth" prop="goodsname">
                    <el-input v-model="goodsForm.goodsname" autocomplete="off" />
                </el-form-item>
                <el-form-item label="价格" :label-width="formLabelWidth" prop="price">
                    <el-input v-model="goodsForm.price" autocomplete="off" />
                </el-form-item>
                <el-form-item label="市场价格" :label-width="formLabelWidth" prop="market_price">
                    <el-input v-model="goodsForm.market_price" autocomplete="off" />
                </el-form-item>
                <el-form-item label="图片" :label-width="formLabelWidth">
                    <el-upload v-model:file-list="fileList" action="#" list-type="picture-card" :on-preview="onPreview"
                        :on-remove="handleRemove" :on-change="onChange" :limit="1">
                        <el-icon>
                            <Plus />
                        </el-icon>
                    </el-upload>
                    <el-dialog v-model="dialogVisible">
                        <img w-full :src="dialogImageUrl" alt="Preview Image" />
                    </el-dialog>
                </el-form-item>
                <el-form-item label="商品规格" :label-width="formLabelWidth" prop="specsid">
                    <el-select v-model="goodsForm.specsid" placeholder="请选择" @change="changeSpecs(false)">
                        <el-option v-for="item in store.getters['specss/getSpecss']" :key="item.id" :label="item.specsname"
                            :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="规格属性" :label-width="formLabelWidth" prop="specsattr">
                    <el-select multiple v-model="goodsForm.specsattr" placeholder="请选择">
                        <el-option v-for="item in specsArr.data" :key="item" :label="item" :value="item"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="是否新品" :label-width="formLabelWidth">
                    <el-radio-group v-model="goodsForm.isnew">
                        <el-radio :label="1" size="large">是</el-radio>
                        <el-radio :label="2" size="large">否</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="是否热卖" :label-width="formLabelWidth">
                    <el-radio-group v-model="goodsForm.ishot">
                        <el-radio :label="1" size="large">是</el-radio>
                        <el-radio :label="2" size="large">否</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="状态" :label-width="formLabelWidth">
                    <el-switch v-model="goodsForm.status"
                        style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949" :active-value="1"
                        :inactive-value="2" />
                </el-form-item>
                <el-form-item label="商品描述" :label-width="formLabelWidth">
                    <div style="border: 1px solid #ccc">
                        <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig"
                            mode="default" />
                        <Editor style="height: 500px; overflow-y: hidden;" v-model="valueHtml" :defaultConfig="editorConfig"
                            mode="default" @onCreated="handleCreated" />
                    </div>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="cancel(goodsRef)">取消</el-button>
                    <el-button type="primary" @click="sure(goodsRef)">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>
<script lang='ts' setup>
//富文本引入
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { defineProps, ref, reactive, defineEmits, defineExpose, shallowRef } from 'vue'
import type { FormInstance, FormRules, UploadProps } from 'element-plus'
import { goodsAdd, goodsEdit, goodsInfo } from '../../request/api'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { useStore } from 'vuex'
let store = useStore()

//富文本
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()

// 内容 HTML
const valueHtml = ref('<p>hello</p>')

const toolbarConfig = {}
const editorConfig = { placeholder: '请输入内容...' }

const handleCreated = (editor: any) => {
    editorRef.value = editor // 记录 editor 实例，重要！
}

//初始值赋值为0
let newId = 0

//父传子 接受数据
let props = defineProps({
    isShow: Boolean,
    isAdd: Boolean
})

//子传父
let emit = defineEmits(['cancel'])

let goodsForm = ref<any>({
    first_cateid: '',//一级分类编号
    second_cateid: '',//二级分类编号
    goodsname: '',//商品名称
    price: '',//商品价格
    market_price: '',//市场价格
    img: '',//商品图片（文件）
    description: '',//商品描述
    specsid: '',//商品规格编号
    specsattr: '',//商品规格属性
    isnew: 1,//是否新品   1-是 2-否
    ishot: 1,//是否热卖推荐 1-是 2-否
    status: 1,//状态1正常2禁用
})


//封装一个确定事件
let goodsRef = ref<FormInstance>()

//关闭x事件
const beforeClose = (done: any) => {
    done()
    cancel(goodsRef.value)
}

//封装一个取消事件
const cancel = (formEl?: FormInstance | undefined) => {
    emit('cancel', false)
    if (!formEl) return
    goodsForm.value = {
        first_cateid: '',//一级分类编号
        second_cateid: '',//二级分类编号
        goodsname: '',//商品名称
        price: '',//商品价格
        market_price: '',//市场价格
        img: '',//商品图片（文件）
        description: '',//商品描述
        specsid: '',//商品规格编号
        specsattr: '',//商品规格属性
        isnew: 1,//是否新品   1-是 2-否
        ishot: 1,//是否热卖推荐 1-是 2-否
        status: 1,//状态1正常2禁用
    }
    //清除表单验证
    formEl.resetFields()
    fileList.value = []
    valueHtml.value = '<p>hello</p>'
}

//图片上传
// let fileList: { url: string }[] = []
const fileList: any = ref([])
const dialogImageUrl = ref('')
const dialogVisible = ref(false)

const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
    console.log(uploadFile, uploadFiles)
}
const onChange: UploadProps['onChange'] = (uploadFile: any) => {
    goodsForm.value.img = uploadFile.raw
}

const onPreview: UploadProps['onPreview'] = (uploadFile) => {
    dialogImageUrl.value = uploadFile.url!
    dialogVisible.value = true
}

const cateArr = reactive<any>({ data: [] })//二级分类
const specsArr = reactive<any>({ data: [] })//规格属性

//封装一个一级分类切换事件，用于获取当前选中状态
const changeCate = (n: any) => {
    let index = store.getters['cate/getCate'].findIndex((item: any) =>
        item.id === goodsForm.value.first_cateid
    )
    cateArr.data = store.getters['cate/getCate'][index].children

    //清空二级分类的双向数据绑定
    if (!n) {
        goodsForm.value.second_cateid = ''
    }
}

const changeSpecs = (n: any) => {
    let index = store.getters['specss/getSpecss'].findIndex((item: any) =>
        item.id === goodsForm.value.specsid
    )
    specsArr.data = store.getters['specss/getSpecss'][index].attrs
    if (!n) {
        goodsForm.value.specsattr = ''
    }
}

//确定事件
const sure = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate((val) => {
        if (val) {
            // console.log(goodsForm.value,'1111');
            //针对于规格属性进行数据格式转化
            goodsForm.value.specsattr = goodsForm.value.specsattr.join(",");
            //富文本格式转换
            goodsForm.value.description = valueHtml.value
            if (props.isAdd) {
                // console.log(goodsForm.value,'2222');
                goodsAdd(goodsForm.value).then(res => {
                    if (res.code == 200) {
                        ElMessage({
                            message: res.msg,
                            type: 'success',
                        })
                        store.dispatch('goods/getGoodsListActions')
                        store.dispatch('goods/getCountAction')
                        cancel(formEl)
                    } else {
                        ElMessage.error(res.msg)
                    }
                })
            } else {
                goodsEdit({ ...goodsForm.value, id: newId }).then(res => {
                    if (res.code == 200) {
                        ElMessage({
                            message: res.msg,
                            type: 'success',
                        })
                        store.dispatch('goods/getGoodsListActions')
                        store.dispatch('goods/getCountAction')
                        cancel(formEl)
                    } else {
                        ElMessage.error(res.msg)
                    }
                })
            }
        }
    })
}

const formLabelWidth = '140px'

//数据回显
const lookup = (id: number) => {
    goodsInfo({ id }).then(res => {
        if (res.code == 200) {
            goodsForm.value = res.list
            newId = id
            fileList.value = goodsForm.value.img
                ? [{ url: goodsForm.value.img }]
                : [];
            //针对于规格属性进行转化
            goodsForm.value.specsattr = goodsForm.value.specsattr.split(",");
            //重新触发change事件目的实现二级联动
            changeCate(true);
            changeSpecs(true);
            //富文本回显转换格式
            valueHtml.value = goodsForm.value.description
        } else {
            ElMessage.error(res.msg);
        }
    })
}

//规则验证
const rules = reactive<FormRules>({
    first_cateid: [
        {
            required: true,
            message: '请选择上级菜单',
            trigger: 'change',
        }
    ],
    second_cateid: [
        {
            required: true,
            message: '请选择上级菜单',
            trigger: 'blur',
        }
    ],
    goodsname: [
        { required: true, message: '请输入菜单名称', trigger: 'blur' },
        { min: 2, max: 8, message: '长度为2-8个字符', trigger: 'blur' },
    ],
    price: [
        { required: true, message: '请输入菜单名称', trigger: 'blur' }
    ],
    market_price: [
        { required: true, message: '请输入菜单名称', trigger: 'blur' }
    ],
    specsid: [
        {
            required: true,
            message: '请选择上级菜单',
            trigger: 'change',
        }
    ],
    specsattr: [
        {
            required: true,
            message: '请选择上级菜单',
            trigger: 'blur',
        }
    ],
})

const action = () => {
    store.dispatch('cate/getCateListActions')
    store.dispatch('specss/getSpecssListActions')
}
action()

defineExpose({
    lookup
})
</script>
<style lang='less' scoped></style>